import os
import time
from pathlib import Path

import oss2
from oss2.credentials import EnvironmentVariableCredentialsProvider
from pymongo import MongoClient

# 定义连接字符串，包含用户名和密码
uri = "mongodb://mongoadmin:maojiawei7750@123.57.232.135:27017/admin?minPoolSize=2&readPreference=primary&ssl=false"

# 创建MongoDB客户端连接
client = MongoClient(uri)

# 选择你要使用的数据库
db = client['test']



# OSS 实例
os.environ['OSS_ACCESS_KEY_ID'] = 'LTAI5tA7HrS5Fb9oNntG9pQb'
os.environ['OSS_ACCESS_KEY_SECRET'] = 'syMxbFBKyiyI54KC6vvO26r48UjHSh'
auth = oss2.ProviderAuthV4(EnvironmentVariableCredentialsProvider())
endpoint = "https://oss-cn-shanghai.aliyuncs.com/"
region = "cn-shanghai"
oss_prefix = "operation/rpa/wechat/"

bucket = oss2.Bucket(auth, endpoint, "szlsfw", region=region)


def save_message(group_name, messages):
    # 获取当前时间
    # 格式化为 yyyy-MM-dd
    date_str = time.strftime('%Y-%m-%d', time.localtime())
    print("日期格式：", date_str)

    # 格式化为 yyyy-MM-dd HH:mm:ss
    datetime_str = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
    print("日期时间格式：", datetime_str)

    """
    处理消息列表，确保图片地址不位于首位，并转换为指定的格式。
    :param messages: 消息列表，其中每个元素是一个包含人名和消息（或图片路径）的列表。
    :return: 转换后的字典。
    """
    result = {}
    for message in messages:
        name = message[0]
        content = message[1]
        # 系统信息忽略
        if name == 'SYS':
            continue

        # 单个文档插入
        post = {"speaker": name,
                "content": content,
                "group_name": group_name,
                "type": 'text',
                "date": date_str,
                "datetime": datetime_str}

        file_path = Path(content)
        if content.startswith('D:\\') or content.startswith('/'):
            # 上传OSS
            with open(content, "rb") as f:
                bucket.put_object(oss_prefix + file_path.name, f)

            # 图片
            post['type'] = 'image'
            post['content'] = ''
            post['image_url'] = 'https://digitaltwin.linkingcloud.cn/' + oss_prefix + file_path.name

        # 存储至mongodb
        posts = db.wechat_message
        post_id = posts.insert_one(post).inserted_id
        print(post_id)


    return result



